<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateGoodsAPIRequest;
use App\Http\Requests\API\UpdateGoodsAPIRequest;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsAttribute;
use App\Models\GoodsContent;
use App\Models\GoodsNumberLog;
use App\Models\GoodsSlideshow;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Repositories\GoodsRepository;
use App\ZL\Controllers\ApiBaseController;
use EasyWeChat\Support\Attribute;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class GoodsController
 * @package App\Http\Controllers\API
 */

class GoodsAPIController extends ApiBaseController
{
    /** @var  GoodsRepository */
    private $goodsRepository;
    protected $model_name = 'App\Models\Goods';
    protected $model_load_array = [
        'categories','attributes','contents','slideshow'
    ];

    protected $search_field_array = [
//        'name'
    ];

    public function __construct(GoodsRepository $goodsRepo)
    {
        $this->goodsRepository = $goodsRepo;
    }

    public function authLimit()
    {
        $type = \request('type');
        $shop_id = \request('shop_id',false);
        $res = [['status',1]];
        if($shop_id && $shop_id>0){
            $res[] =  ['shop_id', $shop_id];
        }
        if($type){
            if($type=='bargain_price'){
                $res[] =  ['sale_price', '>', 0];
            }
        }
        return $res;
    }

    public function index(Request $request)
    {
        $category_id = \request('category_id');
        $is_all = \request('is_all', null);
        $name = \request('name', null);
        $model = $this->modelPipeline([
            'modelGetAuthLimit',
            'modelGetSearch',
            'modelGetSort',
        ]);
        if($name){
            if(strstr($name,'[')!==false || strstr($name,'{')!==false){
                $name = json_decode($name,true);
                $name = $name[1];
                $name = str_replace('%','',$name);
            }
            $name_array = zhong_wen_math($name);
            $model = $model->where(function ($query)use($name_array){
                foreach ($name_array as $item=>$_array) {
                    if($item==0){
                        $query->where('name', 'like', "%$_array%");
                    }else{
                        $query->orWhere('name', 'like', "%$_array%");
                    }
                }
            });
        }
        if($category_id){
            $cate_ids = [];
            $cate = Category::find($category_id);
            foreach ($cate->goods as $goods) {
                $cate_ids[] = $goods->id;
            }
            $model = $model->whereIn('id',$cate_ids);
        }
        if(!$is_all){
            $model = $model->where('is_on_sale', 1);
//            $model = $model->where('sale_start_date', '<=', date('Y-m-d H:i:s'));
//            $model = $model->where('sale_end_date', '>=', date('Y-m-d H:i:s'));
        }
        $model_data = clone $model;
        $count = $model->count();
        $pageSize = request('pageSize',99999999999);
        $pagination = request('pagination',1);
        $pagination = $pagination>0?$pagination:1;
        //分页获取信息
        $model_data = $model_data->orderBy('number', 'desc')->skip($pageSize*($pagination-1))->take($pageSize)->get();

        $list = $this->modelPipeline([
            'collectionGetLoads',
            'modelByAfterGet',
        ],$model_data);

        return responseZK(1,$list,'',['count'=>$count]);
    }

    public function _after_get($data)
    {
        $data->load('categories');
        $data->load('attributesByStatus');
        $data->load('contents');
        $data->load('slideshow');

        $s_arr = [];
        $e_arr = [];
        foreach ($data as $v) {
            $_arr = $v->toArray();
            if(isset($_arr['attributes_by_status'])){
                $_arr['attributes'] = $_arr['attributes_by_status'];
                unset($_arr['attributes_by_status']);
            }
            if($v->number>0){
                $s_arr[] = $_arr;
            }else{
                $e_arr[] = $_arr;
            }
        }
        foreach ($e_arr as $v) {
            $s_arr[] = $v;
        }
        return $s_arr;
    }

    public function _after_find(&$data)
    {
        $data->categories;
        $data->attributes;
        $data->attributesByStatus;
        $data->contents;
        $data->slideshow;
        $array = $data->toArray();
        if(isset($array['attributes_by_status']))
            $array['attributes'] = $array['attributes_by_status'];
        unset($array['attributes_by_status']);
        $data = $array;
    }

    public function addNumber()
    {
        $user_id = Auth::id();
        $goods_id = request('goods_id',0);
        $attribute_id = request('attribute_id',0);
        $number = request('number',0);

        $goods = Goods::find($goods_id);
        if(!$goods)
            return responseZK(0,null,'找不到商品');
        if(!$number)
            return responseZK(0,null,'数量不能为0');
        if($attribute_id){
            $attribute = GoodsAttribute::find($attribute_id);
            if($attribute){
                $attribute->number += $number;
                $attribute->number = $attribute->number>=0?$attribute->number:0;
                $attribute->save();
                $goods->number += $number;
                $goods->number = $goods->number>=0?$goods->number:0;
                $_count = $attribute->number;
                $goods->save();
            }else{
                return responseZK(0,null,'找不到商品商品属性');
            }
        }else{
            if($goods->attributesByStatus->count()>0)
                return responseZK(0,null,'商品缺少属性');
            else{
                $goods->number += $number;
                $goods->number = $goods->number>=0?$goods->number:0;
                $goods->save();
                $_count = $goods->number;
            }
        }

        GoodsNumberLog::create([
            'user_id'=>$user_id,
            'goods_id'=>$goods_id,
            'attribute_id'=>$attribute_id,
            'number'=>$number,
            '_count'=>$_count,
        ]);

        $_arr = $goods->toArray();
        if(isset($_arr['attributes_by_status'])){
            $_arr['attributes'] = $_arr['attributes_by_status'];
            unset($_arr['attributes_by_status']);
        }
        return responseZK(1,$_arr);
    }

    public function beforeStore($id, $request)
    {
        $goods = Goods::find($id);
        $attributes = $request['attributes'];
        $slideshows = $request['slideshows'];
        $content_images = $request['content_images'];
        if(is_string($attributes))
            $attributes = json_decode($attributes,true);
        foreach ($attributes as $attribute) {
            if(!isset($attribute['id']) || !$attribute['id']){
                GoodsAttribute::create($attribute);
            }else{
                GoodsAttribute::where('id',$attribute['id'])->update($attribute);
            }
        }
        if(is_string($slideshows))
            $slideshows = explode(',',$slideshows);
        foreach ($slideshows as $slideshow) {
            $_goodsSlideshow = new GoodsSlideshow([
                'url'=>$slideshow
            ]);
            $goods->slideshow()->save($_goodsSlideshow);
        }

        if(is_string($content_images))
            $content_images = explode(',',$content_images);
        foreach ($content_images as $content_image) {
            $_content = new GoodsContent([
                'url'=>$content_image
            ]);
            $goods->contents()->save($_content);
        }
        return responseZK(1,$goods);
    }

    public function beforeUpdate($id, $request)
    {
        $goods = Goods::find($id);
        $attributes = $request['attributes'];
        if(is_string($attributes))
            $attributes = json_decode($attributes,true);
        foreach ($attributes as $attribute) {
            if(!isset($attribute['id']) || !$attribute['id']){
                GoodsAttribute::create($attribute);
            }else{
                GoodsAttribute::where('id',$attribute['id'])->update($attribute);
            }
        }
        return responseZK(1,$goods);
    }
}
